package com.qingzhuge.netty.common.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
/**
 * @author : zero.xiao
 * @description : 心跳处理器
 * @date :2018/9/28 0028 下午 14:49
 * @since : 1.0.0
 * @modified :
 */
@Slf4j
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {
	private ByteBuf heartBeatSequence;

	public HeartBeatServerHandler(String heartbeat ) {
		heartBeatSequence = Unpooled
				.unreleasableBuffer(Unpooled.copiedBuffer(heartbeat, CharsetUtil.UTF_8));
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleState state = ((IdleStateEvent) evt).state();
			if (state == IdleState.READER_IDLE) {
				ctx.writeAndFlush(heartBeatSequence.duplicate()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
			}
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		log.info("read heartBeat from client {}",msg.toString());
	}
}
